package com.cruising.backend.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.util.RandomUtil;
import com.cruising.backend.entity.Result;
import com.cruising.backend.entity.VerifyCodeRequest;
import com.cruising.backend.utils.ResultUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.util.concurrent.TimeUnit;

import static com.cruising.backend.utils.ResponseCode.responseCode;

@RestController
@RequestMapping("/verify/code")
public class VerifyCodeController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 获取扭曲干扰的验证码
    @GetMapping("/createShearCaptcha")
    public void getShearCaptcha(HttpServletResponse response) {
        // 定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha shearCaptcha = CaptchaUtil.createShearCaptcha(150, 50, 4, 4);

        // 自定义字体
        Font font = new Font("Lucida Sans Unicode", Font.BOLD, 30);
        shearCaptcha.setFont(font);

        // 设置背景颜色
        shearCaptcha.setBackground(new Color(241, 229, 222));

        // 创建字符串
        String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        // 生成一个长度为4的随机字符串，只包含上面指定的字符
        String code = RandomUtil.randomString(chars, 4);

        // 生成验证码图片
        Image image = shearCaptcha.createImage(code);

        // 返回验证码信息
        code = code.toLowerCase();
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue(); // 创建redis容器
        operations.set(code, code, 10, TimeUnit.MINUTES); // 重载, 设置验证码失效时长为10分钟
        responseCode(response, code, image);
    }

    // 验证验证码
    @PostMapping("/verify")
    public Result verifyCode(@RequestBody VerifyCodeRequest request) {
        String inputCode = request.getCode().toLowerCase(); // 将输入的验证码转为小写
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String savedCode = operations.get(inputCode);
        
        if (savedCode != null && savedCode.equals(inputCode)) {
            // 验证成功后删除Redis中的验证码
            stringRedisTemplate.delete(inputCode);
            return ResultUtil.success("验证码验证成功");
        } else {
            return ResultUtil.fail("验证码错误或已过期");
        }
    }
}

